package com.it.common;

import com.alibaba.fastjson.JSON;
import com.it.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        System.out.println("@#%@%%^%&&&^&^");
        System.out.println("token="+token);
        System.out.println("@#@#$^%&%&^*^*(");

        if( !(handler instanceof HandlerMethod)){
            System.out.println("-------");
            return true;
        }

        if(StringUtils.isEmpty(token)){
            Result result =  Result.fail("204","登录失败");
            System.out.println(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        else{
            if(StringUtils.isEmpty(loginService.CheckToken(token))){
                Result result =Result.fail("204","登录失败");
                System.out.println(result);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }

            return true;
        }
    }
}
